package ratelimit

import (
	_ "embed"
	"github.com/redis/go-redis/v9"
	"golang.org/x/net/context"
	"time"
)

//go:embed lua/slide_window.lua
var luaScript string //Redis限流Lua脚本,保证命令的原子性

// RedisSlidingWindowLimiter Redis简单滑动窗口限流器
type RedisSlidingWindowLimiter struct {
	//Redis命令
	cmd redis.Cmdable
	//限流窗口大小
	window time.Duration
	//限流阈值
	threshold int
}

// NewRedisSlidingWindowLimiter 构造函数
func NewRedisSlidingWindowLimiter(cmd redis.Cmdable, window time.Duration, threshold int) *RedisSlidingWindowLimiter {
	return &RedisSlidingWindowLimiter{
		cmd:       cmd,
		window:    window,
		threshold: threshold,
	}
}

func (r *RedisSlidingWindowLimiter) Limit(ctx context.Context, key string) (bool, error) {
	return r.cmd.Eval(ctx, luaScript, []string{key},
		r.window.Milliseconds(),
		r.threshold, time.Now().UnixMilli()).Bool()
}
